import api from "./api";
import axios from "axios";
const API_URL = "https://api.coze.cn/v3/chat"; // 扣子 API 地址
const AUTH_HEADER =
  "Bearer pat_s5qtV4LboDzQ6NFZMNXrRwrohYmZZ6J51iUUlzkCAImNbuCtXiGpbn8Qx79A8CKq"; // 你的授权头
// 聊天相关API
export const chatAPI = {
  // 获取最近聊天列表
  getConversations: async () => {
    try {
      return await api.get("/chat/conversations");
    } catch (error) {
      console.error("获取聊天列表失败", error);
      throw error;
    }
  },

  // 获取与特定用户的对话
  getConversation: async (userId: string) => {
    try {
      return await api.get(`/chat/conversation/${userId}`);
    } catch (error) {
      console.error("获取对话失败", error);
      throw error;
    }
  },

  // 发送消息
  sendMessage: async (receiverId: number, content: string) => {
    try {
      return await api.post("/chat/message", {
        receiverId,
        content,
      });
    } catch (error) {
      console.error("发送消息失败", error);
      throw error;
    }
  },
  // 发送消息给AI助手
  sendAIMessage: async (content: string, userId: string) => {
    console.log(content, "content");

    try {
      // 构建扣子 API 所需的请求数据
      const body = {
        bot_id: "7480527840246169615", // 你的 bot_id
        user_id: userId, // 从用户上下文获取 user_id
        stream: false,
        auto_save_history: false,
        additional_messages: [
          {
            role: "user",
            content: content,
            content_type: "text", // 假设内容类型为文本
          },
        ],
      };

      // 发送 POST 请求到扣子的 API
      const response = await axios.post(API_URL, payload, {
        headers: {
          Authorization: AUTH_HEADER,
          "Content-Type": "application/json",
        },
      });
      console.log(response, "resonse");

      // 检查响应并返回相关数据
      // if (
      //   response &&
      //   response.data &&
      //   response.data.result &&
      //   response.data.result.messages
      // ) {
      //   return response.data;
      // } else {
      //   console.error("Invalid response format from Coze API");
      //   throw new Error("Invalid response format from Coze API");
      // }
    } catch (error) {
      console.log("Coze API response:", error);
      console.error("发送AI消息失败", error);
      throw error;
    }
  },
  // 发送消息给AI助手
  // sendAIMessage: async (content: string) => {
  //   try {
  //     return await api.post("/chat/ai-message", {
  //       content,
  //     });
  //   } catch (error) {
  //     console.error("发送AI消息失败", error);
  //     throw error;
  //   }
  // },

  // 标记消息为已读
  markAsRead: async (messageId: number) => {
    try {
      return await api.put(`/chat/message/${messageId}/read`);
    } catch (error) {
      console.error("标记消息已读失败", error);
      throw error;
    }
  },

  // 获取未读消息数量
  getUnreadCount: async () => {
    try {
      return await api.get("/chat/unread-count");
    } catch (error) {
      console.error("获取未读消息数量失败", error);
      throw error;
    }
  },
};
